'use strict';
module.exports = {
	/**
	 * 检查竞拍的订单状态
	 * @url client/timedTask/pub/test 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		let before = vk.pubfn.getOffsetTime(new Date(), {
			minutes: 60,
			mode: "before", // after 之后 before 之前
		});
		let nopayOrders = await vk.baseDao.selects({
			dbName: "bidding-order", // 主表名
			pageIndex: 1,
			getMain: true,
			pageSize: -1,
			whereJson: {
				status: _.in([0, 1]),//拍下未签合同未付款			
				_add_time: _.lte(before)
			},
			foreignDB: [
				{
					dbName: "bidding-booths", // 副表名
					localKey: "booth_id", // 主表外键字段名
					foreignKey: "_id", // 副表外键字段名
					as: "booth",
					limit: 1, // 当limit = 1时，以对象形式返回，否则以数组形式返回
				}
			]

		});
		console.log(before)
		console.log(nopayOrders)
		if (vk.pubfn.isNotNull(nopayOrders)) {
			for (let index = 0; index < nopayOrders.length; index++) {
				const transaction = await vk.baseDao.startTransaction();
				try {
					const order = nopayOrders[index];
					let num = await vk.baseDao.updateById({
						db: transaction,
						dbName: "bidding-order", // 表名
						id: order._id,
						dataJson: { // 需要修改的数据
							status: -1,
						}
					});
					await vk.baseDao.updateById({
						db: transaction,
						dbName: "bidding-booths", // 表名
						id: order.booth_id,
						dataJson: { // 需要修改的数据
							status: 0,
							nowPrice: order.booth.basePrice,
							endtime: '',
							buy_user: '',
							order_id: '',
							success_bidding_userid: '',
							mark: '超时支付,重拍'
						}
					});
					//设置用户状态为异常
					await vk.baseDao.updateById({
						db: transaction,
						dbName: "uni-id-users", // 表名
						id: order.userid,
						dataJson: { // 需要修改的数据
							biddingstatus: -1,
						}
					});
					let dbName = "bidding-user-punish";
					res.id = await vk.baseDao.add({
						db: transaction,
						dbName,

						dataJson: {
							userid: order.userid,
							status: -1,
							mark: '拍下超时未支付'
						}
					});
					await transaction.commit();
					//标记所有出价为-1
					await vk.baseDao.update({
						dbName: "bidding-biddingprices", // 表名
						whereJson: {
							booth_id: order.booth_id
						},
						dataJson: { // 需要修改的数据
							status: -1,
						}
					});
				} catch (err) {
					// 事务回滚
					await transaction.rollback();
					console.error(`transaction error`, err)
					return {
						code: -1,
						msg: "数据库写入异常,事务已回滚",
						err: {
							message: err.message,
							stack: err.stack
						}
					}
				}

			}

		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
